#include "userlist.h"
#include "ui_userlist.h"
#include <QInputDialog>
#include "url_string.h"
#include <QStandardItemModel>
#include <QMessageBox>
#include "ui_adduser.h"
#include "inputusers.h"
#include <QTextCodec>
#include "common.h"

extern std::string      g_token;
extern std::string      g_url;

UserList::UserList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserList),
    m_manager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);

    // head
    m_items = new QStandardItemModel();
    ui->tableView->setModel(m_items);
    ui->tableView->setShowGrid(true);
    // 设置选中时为整行选中
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置表格的单元为只读属性，即不能编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 设置只能输入数字
    QValidator *validator=new QIntValidator(0,9999,this);
    ui->page_index->setValidator(validator);
    // group init
    initGroupList();
}

UserList::~UserList()
{
    delete ui;
}

void UserList::onAddGroup()
{
    QInputDialog        dlg(this);

    dlg.setLabelText(_T("请输入新的组名"));
    if(0 == dlg.exec())
    {
        return;
    }

    url_string<>        url;
    QString             err;

    url.format("%s?handler=addgroup&name=%u&token=%u",
               g_url.c_str(),
               dlg.textValue().toUtf8().data(),
               g_token.c_str());
    if( ad::http_request(url.c_str(), err) )
    {
        initGroupList();
    }
}

void UserList::onDeleteGroup()
{
    QVariant        group   = ui->grouplist->currentItem()->data(Qt::UserRole);
    QString         str;

    // prompt
    str = _T("确实要删除组\"");
    str += ui->grouplist->currentItem()->text();
    str += _T("\"吗？");
    QMessageBox     confirm(this);

    confirm.setText(str);
    confirm.setIcon(QMessageBox::Question);
    confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    if(QMessageBox::Yes != confirm.exec())
    {
        return;
    }

    url_string<>        url;
    QString             err;

    url.format("%s?handler=deletegroup&gid=%d&token=%u",
               g_url.c_str(), getCurrentGroup(), g_token.c_str());
    if( ad::http_request(url.c_str(), err) )
    {
        initGroupList();
    }
}

void UserList::initGroupList()
{
    url_string<>        url;
    JSONNode            json;
    JSONNode            arr;
    QString             err;

    ui->grouplist->clear();
    ui->userlistpanel->setDisabled(true);
    // set table
    clearTables();

    // request http
    url.format("%s?handler=group&token=%u",
               g_url.c_str(), g_token.c_str());

    // call web request
    if(false == ad::http_request(url.c_str(), err, &json))
    {
        QMessageBox     msg(this);

        msg.setText(err);
        msg.setIcon(QMessageBox::Critical);
        msg.exec();
        return;
    }

    // deal response
    if(false == ad::json_is_array(json, "data"))
    {
        return;
    }

    arr = json["data"].as_array();
    for(json_index_t i = 0; i < arr.size(); i++)
    {
        if( false == ad::json_is_array(arr, i) )
        {
            continue;
        }

        JSONNode    d = arr[i].as_array();
        if(2 > d.size())
        {
            continue;
        }

        QListWidgetItem*    item = new QListWidgetItem;

        item->setText(ad::json_get_string(d, 1));
        item->setData(Qt::UserRole, ad::json_get_string(d, 0).toInt());
        ui->grouplist->addItem(item);
    }
}

void UserList::clearTables()
{
    m_items->clear();
    m_items->setHorizontalHeaderItem(0, new QStandardItem(_T("ID")));
    m_items->setHorizontalHeaderItem(1, new QStandardItem(_T("昵称")));
    m_items->setHorizontalHeaderItem(2, new QStandardItem(_T("邮箱")));
    m_items->setHorizontalHeaderItem(3, new QStandardItem(_T("手机号")));
    m_items->setHorizontalHeaderItem(4, new QStandardItem(_T("QQ号")));
    m_items->setHorizontalHeaderItem(5, new QStandardItem(_T("MSN")));
}

void UserList::showUserLists(int gid, int page)
{
    url_string<>        url;
    QString             err;
    JSONNode            json;
    int                 count   = 0;
    int                 page_size = PAGE_SIZE;

    clearTables();
    url.format("%s?handler=users&gid=%d&page=%d&token=%u&size=%d&s=%u",
               g_url.c_str(), gid, page, g_token.c_str(), page_size,
               m_search.toUtf8().data());
    if(false == ad::http_request(url.c_str(), err, &json, this))
    {
        QMessageBox     msg(this);

        msg.setText(err);
        msg.setIcon(QMessageBox::Critical);
        msg.exec();
        return;
    }

    // parse json
    count = ad::json_get_int(json, "all", 0);
    page = ad::json_get_int(json, "page_cur", 0);
    page_size = ad::json_get_int(json, "page_size", 0);
    if( ad::json_is_array(json, "data") )
    {
        JSONNode&       arr     = json["data"];

        for( json_index_t i = 0; i < arr.size(); i++)
        {
            if( false == ad::json_is_array(arr, i) )
            {
                continue;
            }

            JSONNode&   item = arr[i];
            for(json_index_t k = 0; k < item.size() && k < 6; k++)
            {
                m_items->setItem(i, k,
                    new QStandardItem(ad::json_get_string(item, k)));
            }
        }
    }

    showNavigate(page, count, page_size);
}

void UserList::showNavigate(int page, int all, int pagesize)
{
    wchar_t        buf[1024];

    if(0 == all)
    {
        ui->navigate->setEnabled(false);
        return;
    }

    ui->navigate->setEnabled(true);
    swprintf(buf, sizeof(buf) - 1, L"%d", page + 1);
    ui->page_index->setText(QString::fromWCharArray(buf));

    swprintf(buf, sizeof(buf) - 1, L"/%d页", (all + pagesize - 1) / pagesize);
    ui->page_all->setText(QString::fromWCharArray(buf));

    swprintf(buf, sizeof(buf) - 1, L"共有记录<font color=red>%d</font>条", all);
    ui->page_record->setText(QString::fromWCharArray(buf));

    bool        first   = (0 >= page);
    bool        last    = (page >= ((all + pagesize - 1) / pagesize - 1));

    ui->nvg_first->setEnabled(!first);
    ui->nvg_pre->setEnabled(!first);
    ui->nvg_next->setEnabled(!last);
    ui->nvg_last->setEnabled(!last);
    ui->page_index->setEnabled(!(first && last));
}

int UserList::getCurrentGroup()
{
    QVariant     group   = ui->grouplist->currentItem()->data(Qt::UserRole);

    return group.toInt();
}

int UserList::getCurrentPage()
{
    return ui->page_index->text().toInt();
}

/*
 *change select item
 */
void UserList::onSelectGroup()
{
    ui->search->setText("");
    m_search = "";
    ui->userlistpanel->setDisabled(true);
    showUserLists(getCurrentGroup(), 0);
    ui->userlistpanel->setDisabled(false);
}

void UserList::onAddUser()
{
    QDialog*        dlg    = new QDialog(this);
    Ui::AddUser*    adduser = new Ui::AddUser;
    int             ret;
    QString         h1;

    adduser->setupUi(dlg);
    h1 = _T("添加组\"") + ui->grouplist->currentItem()->text() + _T("\"的用户");
    adduser->m_h1->setText(h1);

    dlg->setWindowTitle(_T("添加新用户"));
    while(true)
    {
        ret = dlg->exec();
        if(0 == ret)
        {
            delete dlg;
            delete adduser;
            return;
        }

        // check input
        if(adduser->m_name->text().length() < 1
            || adduser->m_email->text().length() < 1
            || adduser->m_phone->text().length() < 1
            || adduser->m_qq->text().length() < 1)
        {
            adduser->m_error->setText(_T("<font color=red>请输入完整的信息</font>"));
            continue;
        }

        // send http request
        url_string<>        url;
        url_string<>        post;
        QByteArray          byte;
        QString             err;

        url.format("%s?Handler=adduser&token=%u", g_url.c_str(), g_token.c_str());
        post.format("gid=%d&name=%u&email=%u&phone=%u&qq=%u&msn=",
                    getCurrentGroup(),
                    adduser->m_name->text().toUtf8().data(),
                    adduser->m_email->text().toUtf8().data(),
                    adduser->m_phone->text().toUtf8().data(),
                    adduser->m_qq->text().toUtf8().data()
                    );
        byte.append(post.c_str(), post.length());
        if(false == ad::http_request(url.c_str(), err, NULL, this, &byte))
        {
            adduser->m_error->setText("<font color=red>" + err + "</font>");
            continue;
        }

        delete dlg;
        delete adduser;
        break;
    } // while

    onSelectGroup();
}

void UserList::onNavigateFirst()
{
    onSelectGroup();
}

void UserList::onNavigatePre()
{
    QString     index = ui->page_index->text();
    int         page = atoi(index.toStdString().c_str());
    QVariant    group   = ui->grouplist->currentItem()->data(Qt::UserRole);

    if(page <= 0)
    {
        page = 0;
    }
    else
    {
        page = page - 2;
    }

    showUserLists(group.toInt(), page);
}

void UserList::onNavigate()
{
    QString     index = ui->page_index->text();
    int         page = atoi(index.toStdString().c_str());
    QVariant    group   = ui->grouplist->currentItem()->data(Qt::UserRole);

    if(page <= 0)
    {
        page = 0;
    }
    else
    {
        page = page - 1;
    }

    showUserLists(group.toInt(), page);
}

void UserList::onNavigateNext()
{
    QString     index = ui->page_index->text();
    int         page = atoi(index.toStdString().c_str());
    QVariant    group   = ui->grouplist->currentItem()->data(Qt::UserRole);

    showUserLists(group.toInt(), page);
}

void UserList::onNavigateLast()
{
    QVariant    group   = ui->grouplist->currentItem()->data(Qt::UserRole);

    showUserLists(group.toInt(), 0x7fffffff/PAGE_SIZE);
}

void UserList::onDeleteUsers()
{
    QItemSelectionModel*    selection = ui->tableView->selectionModel();
    QModelIndexList         list      = selection->selectedIndexes();

    if(0 == list.count())
    {
        QMessageBox     box(this);

        box.setIcon(QMessageBox::Critical);
        box.setText(_T("请选择要删除的用户"));
        box.exec();
        return;
    }

    // confirm
    QMessageBox         confirm(this);

    confirm.setIcon(QMessageBox::Question);
    confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    confirm.setText(_T("确实要删除选中的行吗？"));
    if(QMessageBox::Yes != confirm.exec())
    {
        return;
    }

    for(int i = 0; i < list.count(); i += m_items->columnCount())
    {
        int row = list.at(i).row();
        int id = m_items->item(row, 0)->text().toInt();
        url_string<>  url;
        QString err;

        url.format("%s?handler=deleteuser&gid=%d&uid=%d&token=%u",
                   g_url.c_str(), getCurrentGroup(), id, g_token.c_str());
        if(false == ad::http_request(url.c_str(), err))
        {
            QMessageBox     msg(this);

            msg.setText(err);
            msg.setIcon(QMessageBox::Critical);
            msg.exec();
            break;
        }
    }

    showUserLists(getCurrentGroup(), getCurrentPage() - 1);
}

void UserList::onClearUsers()
{
    // confirm
    QMessageBox         confirm(this);

    confirm.setIcon(QMessageBox::Question);
    confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    confirm.setText(_T("确实要清空当前用户组码？"));
    if(QMessageBox::Yes != confirm.exec())
    {
        return;
    }

    url_string<>    url;
    QString         err;

    url.format("%s?handler=clearuser&gid=%d&token=%u",
               g_url.c_str(), getCurrentGroup(), g_token.c_str());
    if(false == ad::http_request(url.c_str(), err))
    {
        QMessageBox     msg(this);

        msg.setText(err);
        msg.setIcon(QMessageBox::Critical);
        msg.exec();
        return;
    }

    showUserLists(getCurrentGroup(), 0);
}

void UserList::onInputUsers()
{
    InputUsers      input(getCurrentGroup(), ui->grouplist->currentItem()->text(), this);

    input.exec();
    showUserLists(getCurrentGroup(), 0);
}

void UserList::onSearch()
{
    m_search = ui->search->text();
    showUserLists(getCurrentGroup(), 0);
}
